<!--
 * @description  : 案件-证据先行登记保存批准书文书
 * @descriptionDetail: 案件-证据先行登记保存批准书文书-fj
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-08-28 15:43:11
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar
      :is-white="false"
      :title="navTitle"
      :custom-back="goBack"
      style="z-index: 99999"
    >
      <view class="white-color" @click="printOrDown(state.canEdit)">
        {{ state.canEdit?'预览':'打印' }}
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="state.canEdit?fContent:fContents" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <view class="main-content">
      <view style="width: calc(100% + 30px);">
        <form-section title="证据先行登记保存批准书"></form-section>
      </view>
      <u-form :model="dataForm" :error-type="errorType" ref="uForm">
        <u-form-item label="当事人" :label-width="labelWidth" :required="true" right-icon="arrow-right">
          <u-input placeholder="请输入" input-align="right" :disabled="!state.canEdit" v-model="dataForm.party" @click="()=>{if(state.canEdit) partySelectShow = true}" />
        </u-form-item>
        <u-form-item label="案由" :label-position="labelPosition" :required="true" prop="causeOfAction" ref="caseChangeRef">
          <u-input type="textarea" height="35" :auto-height="true" placeholder="请选择" :disabled="true" v-model="dataForm.causeOfAction" />
        </u-form-item>
        <u-form-item label="违反条例" :label-position="labelPosition" prop="illegalRequire">
          <u-input
            placeholder="请输入违反条例"
            type="textarea"
            height="35"
            :auto-height="true"
            :disabled="!state.canEdit"
            v-model="dataForm.illegalRequire"
          />
        </u-form-item>
        <u-form-item label="处罚条例" :label-position="labelPosition" prop="illegalClause">
          <u-input
            placeholder="请输入处罚条例"
            type="textarea"
            height="35"
            :auto-height="true"
            :disabled="!state.canEdit"
            v-model="dataForm.illegalClause"
          />
        </u-form-item>
		<u-form-item label="登记保存地点"  :label-position="labelPosition" prop="regAddr">
          <u-input
            placeholder="请输登记保存地点"
            type="textarea"
            height="35"
            :auto-height="true"
            :disabled="!state.canEdit"
            v-model="dataForm.regAddr"
          />
        </u-form-item>
        <u-form-item label="" :label-position="labelPosition">
          <show-goods-info
            :caseUuid="caseParam.caseUuid"
            :dataFromInit="getGoodsApvDtl"
            ref="goodInfoRef"
            :hasDel="state.canEdit"
          >
          </show-goods-info>
        </u-form-item>

        <u-form-item ref="personChangeRef">
          <view class="person-info">
            <view class="p-title">
              <view class="doc-sub-required">
                *
              </view>
              <view class="doc-sub-title">
                承办人（签名）
              </view>
              <view class="uicon-sty" @click="docSub(state.canEdit)">
                <u-icon name="plus-circle" :color="$theme.u_type_primary" size="40"></u-icon>
              </view>
            </view>
            <u-input placeholder="请输入" type="textarea" height="100" :auto-height="true" :disabled="!state.canEdit" v-model="dataForm.undertaker" />
          </view>
        </u-form-item>
        <u-form-item label="文书日期" :label-width="labelWidth" :required="true" right-icon="arrow-right" prop="undertakeDate" ref="dateChangeRef">
          <u-input :disabled="true" input-align="right" placeholder="请选择日期" v-model="dataForm.undertakeDate" @click="()=>{if(state.canEdit)isShowRegDate = true}" />
        </u-form-item>
        <u-form-item label="备注" :label-position="labelPosition">
          <u-input type="textarea" height="100" :disabled="!state.canEdit" :auto-height="true" placeholder="请输入" v-model="dataForm.remark" />
        </u-form-item>
        <u-form-item :label-position="labelPosition" :border-bottom="false" style="padding:0px;">
          <view class="desc-btm" style="display:flex">
            <view>登记保存证据的保存期限为</view>
            <view style="width:76rpx">
              <u-input :disabled="!state.canEdit" :clearable="false" input-align="center" :custom-style="customStyle" placeholder="请输入" v-model="dataForm.shelfLife" />
            </view>
            <view>
              日。
            </view>
          </view>
        </u-form-item>
      </u-form>
    </view>
    <view class="audit-box">
      <view v-for="(ao,index) in approves" :key="index">
        <u-gap height="20" bg-color="#f2f2f2"></u-gap>
        <view class="audit-content">
          <view class="audit-title">
            <text class="audit-require">
              *
            </text>{{ ao.flowNode.displayName }}
          </view>
          <view class="audit-text">
            <u-input type="textarea" placeholder="" :disabled="true" v-model="dataForm['_approveInfo'+ao.gfaCode]" />
          </view>
          <view class="audit-person">
            <u-input placeholder="签名" input-align="right" :disabled="true" :clearable="false" v-model="dataForm['_approvePersonName'+ao.gfaCode]" />
          </view>
          <view class="audit-date">
            <u-input placeholder="年  月  日" input-align="right" :disabled="true" :clearable="false" v-model="dataForm['_approveDate'+ao.gfaCode]" />
          </view>
        </view>
      </view>
    </view>
    <!-- 底部按钮开始 -->
    <view class="submit-btns btn-other-cls" v-if="state.canEdit">
      <u-button plain class="u-btn" type="primary" @click="saveOrSubmit('save')">
        保存
      </u-button>
      <u-button class="u-btn" type="primary" @click="saveOrSubmit('submit')">
        提交
      </u-button>
    </view>
    <!-- 底部按钮结束 -->
    <!-- 人员选择 -->
    <u-popup mode="bottom" height="80%" v-model="personSelectShow">
      <person-selection :params="psParam" @choose="handlerChoosePerson"></person-selection>
    </u-popup>
    <u-calendar :mode="mode" :max-date="yestDate" v-model="isShowRegDate" @change="changeDate('undertakeDate',$event)">
    </u-calendar>
    <u-popup mode="bottom" height="80%" v-model="partySelectShow">
      <select-party-component :params="partyParams" @choose="handlerChooseParty"></select-party-component>
    </u-popup>
  </view>
</template>
<script>
	import caseCommon from '../caseCommonMixin.js';
	import officeService from '@/service/case/office.service.js';
	import caseService from '@/service/case/case.service';
	import PersonSelection from '@/pages/case/components/personSelection.vue';
	import {
		dateUtils,
	} from '@/common/util';
	import ShowDocRegGoodsInfo from '@/pages/case/components/showDocRegGoodsInfo.vue';
	import {
		DOC_STATUS,
	} from '@/common/common_enum.js';
	import SelectPartyComponent from '../components/selectPartyComponent.vue';
	import FormSection from '@/components/form-section.vue';
	import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			'show-goods-info': ShowDocRegGoodsInfo,
			PersonSelection,
			SelectPartyComponent,
			FormSection,
			fabButton
		},
		mixins: [caseCommon, ],
		data() {
			return {
				DOC_STATUS,
				rules: {
					// 当事人
					party: [{
						required: true,
						message: '请填写当事人',
						trigger: ['change', 'blur', ],
					}, ],
					// 案由
					causeOfAction: [{
						required: true,
						message: '请选择案由',
						trigger: ['change', 'blur', ],
					}, ],
					// 承办人签名
					undertaker: [{
						required: true,
						message: '请选择承办人',
						trigger: ['change', 'blur', ],
					}, ],
					// 日期
					undertakeDate: [{
						required: true,
						message: '请选择日期',
						trigger: ['change', 'blur', ],
					}, ],
				},
				errorType: ['border-bottom', 'message', ],
				isTrue: true,
				labelPosition: 'top',
				labelWidth: '280',
				dataForm: {},
				employeeLst: [], // 选择人员数据
				caseParam: {}, // 上个页面传过来的参数
				isShowRegDate: false,
				mode: 'date',
				maxDate: '2099-12-31',
				yestDate: this.$u.timeFormat(Date.now()),
				isAction: false,
				isPerson: false,
				doc: {},
				personSelectShow: false,
				psParam: {
					min: 2,
				},
				approves: [], // 审核审批信息
				isApprovePerson: false, // 是否是审核人
				goodsListShow: true,
				goodsList: [],
				titSty: {
					fontSize: '32rpx',
					marginLeft: '-15px',
				},
				partySelectShow: false,
				partyList: [], // 当事人列表
				partyParams: {}, // 传给当事人选择页面的参数
				customStyle: {
					backgroundColor: this.$theme['u_bg_color'],
					display: 'block',
				},
				fromInDoc: true,
				fContent: [{
					iconPath: require('@/static/oview.png'),
					selectedIconPath: require('@/static/oview.png'),
					text: '预览',
					active: false,
				}],
				fContents: [{
					iconPath: require('@/static/dy.png'),
					selectedIconPath: require('@/static/dy.png'),
					text: '打印',
					active: false,
				}]
			};
		},
		computed: {
			arrow() {
				return this.goodsListShow ? 'down' : 'right';
			},
		},
		watch: {
			isShowRegDate(newValue, oldValue) {
				this.$refs.dateChangeRef.validation();
			},
			isAction(newValue, oldValue) {
				this.$refs.caseChangeRef.validation();
			},
			isPerson(newValue, oldValue) {
				this.$refs.personChangeRef.validation();
			},
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad(preParams) {
			this.caseParam = this.getRouteParam();
			this.psParam.caseUuid = this.caseParam.caseUuid;
		},
		mounted() {
			this.docStep((docInfo) => {
				this.doc = docInfo;
				this.setRightBtns();
			});
			this.initDocData();
		},
		methods: {
			docSub(flag) {
				if (flag) {
					console.log(flag);
					this.personSelectShow = true;
					this.psParam = {
						min: 2,
						caseUuid: this.caseParam.caseUuid,
					};
				}
			},
			initDocData() {
				try {
					let parms = {
						id: this.caseParam.id,
						docUuid: this.caseParam.docUuid,
						bizUuid: this.caseParam.bizUuid,
					};
					this.fromInDoc = true;
					this.$modal.showLoading('加载中');
					// 先行登记保存审批表数据，流程信息
					Promise.all([officeService.docRevokeApprove(parms), officeService.approves({
						id: this.caseParam.id,
						docUuid: this.caseParam.docUuid,
					}), ]).then(
						(_docs) => {
							console.log('数据', _docs);
							let [tiInfo, rs, ] = [{}, {}, ];
							if (_docs[0].data.length === 2) {
								tiInfo = _docs[0].data[0];
								rs = _docs[0].data[1];
								Object.keys(tiInfo).forEach((key) => {
									rs[key] = tiInfo[key];
								});
							} else {
								rs = _docs[0].data[0];
							}
							this.dataForm = rs;
							this.approves = _docs[1].data;
							this.approves.forEach((item) => {
								this.dataForm['_approveInfo' + item.gfaCode] = item.approveInfo || '';
								this.dataForm['_approvePersonUuid' + item.gfaCode] = item.approvePersonUuid || '';
								this.dataForm['_approvePersonName' + item.gfaCode] = item.approvePersonName || '';
								this.dataForm['_approveDate' + item.gfaCode] = item.approveDate ?
									item.approveDate :
									item.step == item.flowNode.nodeCode ?
									dateUtils.dateFormat('yyyy年MM月dd日', new Date()) :
									'';
							});
							this.goodsList = rs.goods || [];
							this.$refs['goodInfoRef'].setStaticData(this.goodsList);
							this.fromInDoc = false;
							this.$modal.hideLoading();
							this.getPartyInfoList();
						},
						(err) => {
							this.$modal.hideLoading();
							this.$u.toast(err);
							this.$u.hideLoading();
						}
					);
				} catch (e) {
					this.$modal.hideLoading();
					this.$u.toast(e);
					this.$u.hideLoading();
				}
			},
			// 获取当事人list（多选）
			getPartyInfoList() {
				caseService
					.getPartyInfoList(this.caseParam.bizUuid)
					.then((res) => {
						if (!res.success) return;
						this.partyList = res.data.length > 0 ? res.data : [];
						this.partyList.forEach((itm) => {
							if (this.dataForm.partyUuids.indexOf(itm.partyUuid) != -1) {
								itm.checked = true;
							}
						});
						this.partyParams = {
							list: this.partyList,
							selUsersStr: this.dataForm.partyUuids,
						};
					})
					.catch((err) => {
						this.partyList = [];
						console.log(err);
					});
			},
			// 选择当事人回调事件
			handlerChooseParty(e) {
				this.partySelectShow = false;
				this.dataForm.party = e.partyNames;
				this.partyParams.selUsersStr = e.partyUuids;
				this.dataForm.partyUuids = e.partyUuids;
			},
			getGoodsApvDtl() {
				return new Promise((resolve, reject) => {
					if (this.fromInDoc) {
						resolve({
							noPage: 1,
							data: this.goodsList,
						});
						return;
					}
					caseService
						.getGoodsApvDtl({
							caseUuid: this.caseParam.caseUuid,
						})
						.then((res) => {
							this.goodsList = !res.success ? [] : [...res.data, ];
							resolve({
								noPage: 1,
								data: this.goodsList,
							});
						})
						.catch((e) => {
							this.goodsList = [];
							resolve({
								noPage: 1,
								data: this.goodsList,
							});
						});
				});
			},
			// 设置右侧标题
			setRightBtns() {
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight(this.state.canEdit ? '预览' : '打印', () => {
					this.printOrDown(this.state.canEdit);
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.printOrDown(this.state.canEdit);
				}
			},
			// 打印/预览
			printOrDown(flag) {
				if (flag) {
					// 调接口预览
					this.saveOrSubmit('preview');
				} else {
					this.downloadFile(this.doc.pdfFileId);
				}
			},
			downloadFile(fileId, titleName, isDownload) {
				let pdfIds = fileId;
				if (!pdfIds) {
					this.$u.toast('没有文书');
					return;
				}
				this.setRouteParam({
					fileId: pdfIds,
					fileName: titleName,
					isDownload: isDownload,
				});
				this.$u.route('pages/commonPage/printerComponent');
			},
			changeDate(type, e) {
				this.dataForm[type] = dateUtils.dateFormat('yyyy年MM月dd日', new Date(e.result));
			},
			// 选择执行人
			handlerChoosePerson(e) {
				this.personSelectShow = false;
				// 提交选择审核人
				if (this.isApprovePerson) {
					let nextP = [];
					e.forEach((item) => {
						nextP.push(item.personId);
					});
					this.submitDocInfo('submit', nextP.join(','));
				} else {
					this.employeeLst = [...e, ];
					let tIds = [];
					let tNames = [];
					this.employeeLst.forEach((el) => {
						tIds.push(el.personUuid);
						tNames.push(el.personName + '(' + el.leCertNo + ')');
					});
					this.dataForm['undertakerUuids'] = tIds.join(',');
					this.dataForm['undertaker'] = tNames.join(',');
				}
			},
			// 表单验证
			validForm() {
				let basicValid = false;
				this.$refs.uForm.validate((valid) => {
					if (valid) {
						if (!this.dataForm.party) {
							this.$u.toast('请选择当事人!');
							return;
						}
						basicValid = true;
						console.log('表单验证通过');
					} else {
						basicValid = false;
						console.log('表单验证失败');
					}
				});
				return basicValid;
			},
			saveOrSubmit(type) {
				// 点击提交、保存按钮
				let flag = this.validForm();
				if (flag) {
					if (this.dataForm.goods.length > 0) {
						if (type == 'submit') {
							// 选择审核人
							this.choseAuditPsr('docGoodsApv');
						} else {
							this.submitDocInfo(type);
						}
					} else {
						this.$modal.alert('物品信息不能为空！');
					}
				}
			},
			// 保存/提交接口
			submitDocInfo(type, nextPersons) {
				try {
					let {
						id,
						docUuid,
						titemUuid,
					} = this.caseParam;
					this.dataForm.caseUuid = this.caseParam.caseUuid;
					type == 'save' && this.$u.loading('数据保存中...');
					this.dataForm.goods = this.$refs.goodInfoRef.goodsList;
					officeService.saveDocGoodsApv(this.dataForm, docUuid, titemUuid, id, this.caseParam.type).then((res) => {
						this.$u.hideLoading();
						if (res.success) {
							this.dataForm = res.bean;
							try {
								if (!this.doc) this.doc = res.data[0];
							} catch (e) {
								console.log(e);
							}
							if (type == 'submit') {
								this.$u.loading('数据提交中...');
								officeService.submitDocGoodsApv(this.dataForm, docUuid, titemUuid, id, this.caseParam.type, nextPersons).then((res) => {
									this.$u.hideLoading();
									this.$u.toast(res.msg);
									this.saveBehaviorLog(1, this.caseParam, this.doc);
									if (res.success) {
										this.backPrev({
											paramKey: 'offiList',
											param: {
												caseUuid: this.caseParam.bizUuid,
												caseCode: this.caseParam.caseCode,
												caseType: this.caseParam.caseType,
											},
										});
									}
								});
							} else if (type == 'preview') {
								officeService.buildLocalPunish('/record/doc-goods-apv', this.doc.docInsUuid).then((pdfId) => {
									if (pdfId.success) {
										this.downloadFile(pdfId.bean, '预览', false);
									} else {
										this.$u.toast(pdfId.msg);
									}
								});
							} else {
								this.saveBehaviorLog(0, this.caseParam, this.doc);
								this.$u.toast(res.msg);
							}
						} else {
							this.$u.hideLoading();
							this.$u.toast(res.msg);
						}
					});
				} catch (e) {
					this.$u.hideLoading();
				}
			},
			// 提交时选择审核人
			choseAuditPsr(gfaCode) {
				this.isApprovePerson = true;
				this.psParam = {
					min: 1,
					selectedPsrLst: [],
					dataHandler: (psrName) => {
						return caseService
							.getNextFlowUsers({
								page: 1,
								limit: 20,
								personName: psrName,
								gfCode: gfaCode,
							})
							.then((res) => {
								if (res.success) {
									return res.data;
									// return res.data.map((item) => {
									//   console.log(item, 'item');
									//   item['departName'] = item.deptName;
									// });
								} else {
									return [];
								}
							});
					},
				};
				this.personSelectShow = true;
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import '../case_common.scss';

	.page {
		padding: 0;
	}

	/deep/ .main-content .u-cell-item-box {
		margin-left: -15px;
	}

	.u-td {
		white-space: nowrap;
		overflow: hidden;
	}
</style>
